<template>
  <div>
    <Head-Top></Head-Top>
    <div class="all_con">
      <div class="search_view">
        <el-form :model="ruleForm1" status-icon :rules="rules1" ref="ruleForm1" label-width="100px"
                 class="demo-ruleForm">
          <div style="display: flex;margin-top: 20px">
            <el-form-item style="margin-left: 20px" label-width="0px" prop="phoneName">
              <el-input size="medium" placeholder="输入手机号或用户名" type="text" v-model="ruleForm1.phoneName"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label-width="0px">
              <el-button class="submit_btn" size="medium" type="primary" @click="submitForm('ruleForm1')">搜索</el-button>
            </el-form-item>
          </div>
        </el-form>
        <el-button @click="exportExcel()" type="primary">导出报表</el-button>
        <div>
          <el-button @click="handleAddAgent()" size="small" type="primary">新增代理商</el-button>
        </div>
      </div>
      <div class="table_container">
        <div>
          <Agent-Table v-on:handleRecover="handleRecover" v-on:handleFreeze="handleFreeze" v-on:handleEdit="handleEdit"
                       :itemData="agentInfo.tableData"/>
        </div>
        <el-dialog
          title="代理商编辑"
          :visible.sync="dialogVisible"
          width="30%">
          <div>
            <el-form :model="editAgentInfo.formDatas" status-icon :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm"
                     label-position="right">
              <el-form-item label="真实姓名" prop="realname">
                <el-col :span="10">
                  <el-input placeholder="被编辑代理的真实姓名" type="text" v-model="editAgentInfo.formDatas.realname"></el-input>
                </el-col>
              </el-form-item>

              <el-form-item label="身份证号码" prop="IDnumber">
                <el-col :span="10">
                  <el-input placeholder="被编辑代理的居民身份证号码" type="number" v-model="editAgentInfo.formDatas.IDnumber"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="代理商地址">
                <el-col :span="10">
                  <v-distpicker :province="editAgentInfo.range.province" :city="editAgentInfo.range.city" :area="editAgentInfo.range.area"  @selected="onSelected"></v-distpicker>
                </el-col>
              </el-form-item>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible=false">取 消</el-button>
              <el-button type="primary" @click="confirmEdit('ruleForm2')">确 定</el-button>
          </span>
        </el-dialog>

        <div class="pageination">
          <span style="float: left" class="demonstration">当前第1页</span>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page.sync="agentInfo.currentPage"
            :page-sizes="[10, 20 ,100, 200, 500,1000]"
            :page-size="agentInfo.limit"
            layout="sizes, prev, pager, next"
            :total="agentInfo.allTableData.length">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import HeadTop from '../components/HeadTop'
  import {mapActions, mapState, mapMutations} from 'vuex'
  import AgentTable from "../components/AgentTable";
  import FileSaver from 'file-saver'
  import {updateUserData} from '../api/getData'
  import XLSX from 'xlsx'
  import VDistpicker from 'v-distpicker'
  export default {
    name: "AgentManage",
    components: {
      AgentTable,
      HeadTop,
    },
    data() {
      let validatePhoneName = (rule, value, callback) => {
        callback();
      }
      let validaterealName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入代理姓名'));
        } else {
          callback();
        }
      }
      let validateIDnumber = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入代理身份证号码'));
        } else {
          callback();
        }
      }
      return {
        ruleForm1: {
          phoneName: '',
        },
        rules1: {
          phoneName: [
            {validator: validatePhoneName, trigger: 'blur'}
          ]
        },
        rules2: {
          realname: [
            {validator: validaterealName, trigger: 'blur'}
          ],

          IDnumber: [
            {validator: validateIDnumber, trigger: 'blur'}
          ],
        },
        dialogVisible:false
      }
    },
    computed: {
      ...mapState(['agentInfo','editAgentInfo']),
    },
    methods: {
      ...mapActions(['getEditAgent', 'getAgentList', 'upDateAgentInfo', 'getAgentListByQuery',]),
      ...mapMutations(['changeAgentList','changeAgentAddress']),
      onSelected(data){
        this.changeAgentAddress(data)
      },
      confirmEdit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params={...this.editAgentInfo.formDatas}
            updateUserData(params)
              .done(res=>{
                if(res.message=='success'){
                  this.$message({
                    type:'success',
                    message:'修改成功！'
                  })
                  this.dialogVisible=false
                  this.getAgentList()
                }
              })
          }else {
            return false;
          }
        });
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let {phoneName} = this.ruleForm1
            this.getAgentListByQuery({requirement: phoneName})
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      exportExcel() {
        /* generate workbook object from table */
        let wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
        /* get binary string as output */
        let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
        try {
          FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), '代理商.xlsx')
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      },
      handleRecover({index, user_id}) {
        let status = '1'
        this.upDateAgentInfo({index, user_id, status})
      },
      handleEdit({index, user_id}) {
        // this.$router.push({
        //   path: 'edit_agent',
        //   query: {
        //     user_id
        //   }
        // })
        this.dialogVisible=true
        this.getEditAgent({user_id})

      },
      handleFreeze({index, user_id}) {
        let status = '3'
        this.upDateAgentInfo({index, user_id, status})
      },
      handleSizeChange(limit) {
        this.changeAgentList({limit})
        // console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.changeAgentList({val})
      },
      handleAddAgent() {
        this.$router.push({
          path: '/add_agent',
        })
      }
    },
    mounted() {
      this.getAgentList()
    }
  }
</script>

<style lang="less" scoped>
  @import "../style/table.less";

  .search_view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 100px;
  }
</style>
